package com.spzx.product.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: ThreadPoolConfig
 * Description:
 *
 * @Author linz
 * @Creat 2025/3/19 20:17
 * @Version 1.00
 */
@Configuration
public class ThreadPoolConfig {
    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        int processorCount = Runtime.getRuntime().availableProcessors(); // 获取CPU数量
        int corePoolSize = processorCount ; //设置为CPU数量
        int maximumPoolSize = processorCount * 2; // 最大线程数量为CPU数量的两倍
        int keepAliveTime = 60; //保持60秒活跃时间

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                Executors.defaultThreadFactory(),
                //拒绝策略
                (runnable,executor)->{
                    try {
                        //通过短暂休眠来等待线程池中有空闲资源
                        Thread.sleep(200);
                    }catch (InterruptedException e){}
                    //再次将拒绝任务提交给线程池执行
                    executor.submit(runnable);
                });

        //线程会在需要时创建
        return threadPoolExecutor;
    }
}
